package cn.edu.cumt.ec.demo.service.impl;

import cn.edu.cumt.ec.demo.entity.Role;
import cn.edu.cumt.ec.demo.entity.User;
import cn.edu.cumt.ec.demo.mapper.RoleMapper;
import cn.edu.cumt.ec.demo.mapper.UserMapper;
import cn.edu.cumt.ec.demo.security.JwtUser;
import cn.edu.cumt.ec.demo.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2021-11-03
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        JwtUser jwtUser = userMapper.getJwtUserByPhoneNumber(username);
        if (jwtUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 创建List集合，用来保存用户权限，GrantedAuthority对象代表赋予给当前用户的权限
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 获得当前用户权限集合
        List<Role> roles=roleMapper.listByUserId(jwtUser.getUserId());
        for (Role role : roles) {
            // 将关联对象Role的authority属性保存为用户的认证权限
            authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        jwtUser.setAuthorities(authorities);
        return jwtUser;
    }
}
